package com.wxzhou.wangzhuan.service;

import com.wxzhou.wangzhuan.util.RedisKeyUtil;
import io.quarkus.redis.datasource.ReactiveRedisDataSource;
import io.quarkus.redis.datasource.keys.ReactiveKeyCommands;
import io.quarkus.redis.datasource.value.ReactiveValueCommands;
import io.smallrye.mutiny.Uni;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;

import java.time.Duration;
import java.util.Optional;
import java.util.UUID;

/**
 * Token服务 - 替代Sa-Token的token管理
 */
@ApplicationScoped
public class TokenService {

    @Inject
    ReactiveRedisDataSource redisDataSource;
    
    @Inject
    RedisKeyUtil redisKeyUtil;

    /**
     * 生成Token
     */
    public Uni<String> generateToken(String userId, String deviceId) {
        String token = UUID.randomUUID().toString();
        String key = redisKeyUtil.buildTokenKey(token);
        String value = userId + ":" + deviceId;

        // 存储到Redis，使用配置的过期时间
        ReactiveValueCommands<String, String> valueCommands = redisDataSource.value(String.class);
        return valueCommands.setex(key, redisKeyUtil.getTokenExpireSeconds(), value)
                .onItem().transform(response -> token);
    }

    /**
     * 验证Token
     */
    public Uni<Optional<String>> validateToken(String token) {
        if (token == null || token.isEmpty()) {
            return Uni.createFrom().item(Optional.empty());
        }

        String key = redisKeyUtil.buildTokenKey(token);
        ReactiveValueCommands<String, String> valueCommands = redisDataSource.value(String.class);
        return valueCommands.get(key)
                .onItem().transform(response -> {
                    if (response != null) {
                        return Optional.of(response);
                    }
                    return Optional.empty();
                });
    }

    /**
     * 刷新Token过期时间
     */
    public Uni<Void> refreshToken(String token) {
        String key = redisKeyUtil.buildTokenKey(token);
        ReactiveKeyCommands<String> keyCommands = redisDataSource.key(String.class);
        return keyCommands.expire(key, Duration.ofSeconds(redisKeyUtil.getTokenExpireSeconds()))
                .onItem().transform(response -> null);
    }

    /**
     * 删除Token
     */
    public Uni<Void> deleteToken(String token) {
        String key = redisKeyUtil.buildTokenKey(token);
        ReactiveKeyCommands<String> keyCommands = redisDataSource.key(String.class);
        return keyCommands.del(key)
                .onItem().transform(response -> null);
    }

    /**
     * 从Token中提取用户ID
     */
    public String extractUserId(String tokenValue) {
        if (tokenValue != null && tokenValue.contains(":")) {
            return tokenValue.split(":")[0];
        }
        return "0";
    }

    /**
     * 从Token中提取设备ID
     */
    public String extractDeviceId(String tokenValue) {
        if (tokenValue != null && tokenValue.contains(":")) {
            return tokenValue.split(":")[1];
        }
        return null;
    }
} 